package dtaskboard.entities;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashSet;
import java.util.List;

import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;

import com.ibm.icu.util.Calendar;

import dtaskboard.client.dto.HistoryDTO;
import dtaskboard.client.dto.SprintDTO;
import dtaskboard.client.dto.SprintStatus;

@Entity
public class Sprint {
  private Long id;
  private Long plannedHours;
  private Long achievedHours;
  private SprintStatus status;
  private Collection<History> histories;
  private Date startDate;
  private Date endDate;


  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  public Long getId() {
    return this.id;
  }

  public void setId(Long id) {
    this.id = id;
  }

  public Long getPlannedHours() {
    return this.plannedHours;
  }

  public void setPlannedHours(Long plannedHours) {
    this.plannedHours = plannedHours;
  }

  @OneToMany
  public Collection<History> getHistories() {
    if (this.histories == null) {
      this.histories = new HashSet<History>();
    }
    return this.histories;
  }

  public void setHistories(Collection<History> histories) {
    this.histories = histories;
  }

  public Long getAchievedHours() {
    return this.achievedHours;
  }

  public void setAchievedHours(Long achievedHours) {
    this.achievedHours = achievedHours;
  }

  @Enumerated(EnumType.STRING)
  public SprintStatus getStatus() {
    return this.status;
  }

  public void setStatus(SprintStatus status) {
    this.status = status;
  }

  public SprintDTO toDTO() {
    SprintDTO dto = new SprintDTO();
    List<HistoryDTO> histories = new ArrayList<HistoryDTO>();
    for (History h : this.getHistories()) {
      histories.add(h.toDTO());
    }
    dto.setHistories(histories);
    dto.setStartDate(this.startDate);
    dto.setEndDate(this.endDate);
    if (this.achievedHours != null) {
      dto.setAchievedHours(this.achievedHours.intValue());
    }
    dto.setPlannedHours(this.plannedHours.intValue());

    GregorianCalendar end = new GregorianCalendar();
    end.setTime(this.endDate);
    GregorianCalendar start = new GregorianCalendar();
    start.setTime(this.startDate);
    int diff = end.get(Calendar.DAY_OF_YEAR) - start.get(Calendar.DAY_OF_YEAR);

    if (diff < 0) {
      dto.setDays(365 + diff);
    } else {
      dto.setDays(diff);
    }


    return dto;
  }

  public Date getStartDate() {
    return this.startDate;
  }

  public void setStartDate(Date startDate) {
    this.startDate = startDate;
  }

  public Date getEndDate() {
    return this.endDate;
  }

  public void setEndDate(Date endDate) {
    this.endDate = endDate;
  }
}
